import { defineStore, acceptHMRUpdate } from "pinia";
import { invokeAPi, invokeAsyncAPi } from "@/xz-fn";
import uaBrowser from "ua-browser";
import { compareVersion } from "@/utils";


const formatMerchant = (id: string) => {
  const merchantMap = {
    '3448045082': '360',
    'lxoem': 'lx'
  }
  const target = merchantMap[id as keyof typeof merchantMap]
  console.log('merchant_id：', id, ' 渠道：', target)
  return target || ''
}

export const systemAppStore = defineStore({
  id: "system",
  state: () => ({
    appInfo: {
      appID: import.meta.env.VITE_APP_APPID, // 客户端id
      channel: "", // 渠道信息
      uuid: "", // 设备信息
      device_name: "", // 设备名称
      version: "1.0.0.0", // 版本号
      allPackages: [import.meta.env.VITE_APP_PKGID],
      merchantId: import.meta.env.VITE_APP_MERCHANTID, // 主体id
      projectId: "",
      trialPeriod: 0, // 可领试用时长
      merchant: ''
    },
    showTsb: true,
    sysInfo: {
      os_name: ""
    },
    pubkey: "",
    appCfg: {
      site: import.meta.env.VITE_APP_ORIGIN,
      name: import.meta.env.VITE_APP_NAME,
      logo: import.meta.env.VITE_APP_LOGO,
      userProtocol: import.meta.env.VITE_APP_ORIGIN + "/user-protocol.html",  // 用户协议
      cdkProtocol: import.meta.env.VITE_APP_ORIGIN + "/cdk-protocol.html", // 兑换码协议
      vipProtocol: import.meta.env.VITE_APP_ORIGIN + "/vip-protocol.html", // 会员协议
      cycleProtocol: import.meta.env.VITE_APP_ORIGIN + "/cycle-pay-protocol.html", // 自动续费协议
    }
  }),
  actions: {
    getDeviceInfo() {
      return invokeAsyncAPi("fq_GetClientInfo")
        .then((deviceInfo: any) => {
          this.appInfo.appID = deviceInfo.app_id + "";
          this.appInfo.channel = deviceInfo.union_id + ""; // 后端接口需要字符类型
          this.appInfo.uuid = deviceInfo.pcid;
          this.appInfo.device_name = deviceInfo.device_name;
          this.appInfo.version = deviceInfo.version || "1.0.2.2";
          this.appInfo.merchantId = deviceInfo.merchant_id;
          this.appInfo.projectId = deviceInfo.project_id;
          this.appInfo.merchant = formatMerchant(invokeAPi('xz_get_merchant_Id'))

          if (compareVersion(deviceInfo.version, '1.0.0.4') <= 0) {
            this.appInfo.allPackages = [import.meta.env.VITE_APP_PKGID_OLD]
          }

          if (['lx'].includes(this.appInfo.merchant)) {
            this.showTsb = false
          }

          if(deviceInfo.os_name){
            this.sysInfo.os_name = deviceInfo.os_name
          }else{
            const browser = uaBrowser(navigator.userAgent);
            this.sysInfo.os_name = `${browser.os} ${browser.osVersion}`;
          }
        });
    }
  }
});
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(systemAppStore, import.meta.hot));
}
